package com.jsmile.cloud.authc.sys.repo;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsmile.cloud.authc.api.req.sys.ReqSysUserQuery;
import com.jsmile.cloud.authc.api.res.ResSysUser;
import com.jsmile.cloud.authc.sys.dao.SysUserDao;
import com.jsmile.cloud.authc.sys.model.SysUser;
import com.jsmile.mall.api.enums.JSmileCacheEnum;
import com.jsmile.mall.api.enums.SfEnum;
import com.jsmile.mall.api.kit.DateKit;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 龚亮
 * @version 1.0
 * @desc 为了薪资破万，还是睡一会儿吧...!
 * @date 2020年10月16日 02:46:20
 */
@Service
@Slf4j
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class SysUserSearchRepository extends ServiceImpl<SysUserDao, SysUser> {

    /**
     * @param username
     *            用户名、邮箱、手机号码
     * @param tenantId
     *            租户id
     * @param userType
     *            用户类型
     * @return 用户信息
     */
    @Cacheable(value = JSmileCacheEnum.JSmileCacheName.oneDay, key = "#username+'_'+#tenantId+'_'+#userType")
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public ResSysUser findByUsername(String username, Long tenantId, Integer userType) {
        return this.baseMapper.findByUsername(username, tenantId, userType, SfEnum.F.getValue());
    }

    public IPage<SysUser> pageQuery(ReqSysUserQuery reqSysUserQuery) {
        return this.baseMapper.selectPage(reqSysUserQuery.getPage(), getQueryWrapper(reqSysUserQuery));
    }

    private Wrapper getQueryWrapper(ReqSysUserQuery reqSysUserQuery) {
        return new QueryWrapper<SysUser>().lambda().eq(null != reqSysUserQuery.getCurTenantId(), SysUser::getTenantId, reqSysUserQuery.getCurTenantId())
            .eq(null != reqSysUserQuery.getDeptId(), SysUser::getDeptId, reqSysUserQuery.getDeptId())
            .eq(null != reqSysUserQuery.getEnable(), SysUser::getEnable, reqSysUserQuery.getEnable())
            .ge(null != reqSysUserQuery.getStartDate(), SysUser::getCreateTime, DateKit.beginOfDay(reqSysUserQuery.getStartDate()))
            .le(null != reqSysUserQuery.getEndDate(), SysUser::getCreateTime, DateKit.endOfDay(reqSysUserQuery.getEndDate())).orderByDesc(SysUser::getCreateTime);// sort,createTime倒序
    }

}
